Skip to content

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

Remove git convenience functions, enforce explicit paths

Maximilian Roos4c5051e24c57
diff --git a/src/git.rs b/src/git.rs
index 167b9f45b..123962515 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -143,14 +143,9 @@ fn parse_worktree_list(output: &str) -> Result<Vec<Worktree>, GitError> {
Ok(worktrees)
}
-/// Get the default branch name using a hybrid approach:
+/// 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() -> Result<String, GitError> {
- get_default_branch_in(std::path::Path::new("."))
-}
-
-/// Get the default branch name for a repository at the given path
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) {
@@ -223,12 +218,7 @@ fn cache_default_branch(path: &std::path::Path, branch: &str) -> Result<(), GitE
Ok(())
}
-/// Check if a git branch exists (local or remote)
-pub fn branch_exists(branch: &str) -> Result<bool, GitError> {
- branch_exists_in(std::path::Path::new("."), branch)
-}
-
-/// Check if a git branch exists in the repository at the given path
+/// 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(
@@ -251,12 +241,7 @@ pub fn branch_exists_in(path: &std::path::Path, branch: &str) -> Result<bool, Gi
Ok(result.is_ok())
}
-/// Get the current branch name, or None if in detached HEAD state
-pub fn get_current_branch() -> Result<Option<String>, GitError> {
- get_current_branch_in(std::path::Path::new("."))
-}
-
-/// Get the current branch name for a repository at the given path
+/// 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();
@@ -268,23 +253,13 @@ pub fn get_current_branch_in(path: &std::path::Path) -> Result<Option<String>, G
}
}
-/// Get the git common directory (the actual .git directory for the repository)
-pub fn get_git_common_dir() -> Result<PathBuf, GitError> {
- get_git_common_dir_in(std::path::Path::new("."))
-}
-
-/// Get the git common directory for a repository at the given path
+/// 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 (may be different from common-dir in worktrees)
-pub fn get_git_dir() -> Result<PathBuf, GitError> {
- get_git_dir_in(std::path::Path::new("."))
-}
-
-/// Get the git directory for a repository at the given path
+/// 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()))
@@ -305,12 +280,7 @@ pub fn worktree_for_branch(branch: &str) -> Result<Option<PathBuf>, GitError> {
Ok(None)
}
-/// Check if the working tree is dirty (has uncommitted changes)
-pub fn is_dirty() -> Result<bool, GitError> {
- is_dirty_in(std::path::Path::new("."))
-}
-
-/// Check if the working tree is dirty in the repository at the given path
+/// 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> {
// Check for any changes in the working tree or index
let output = std::process::Command::new("git")
@@ -328,22 +298,12 @@ pub fn is_dirty_in(path: &std::path::Path) -> Result<bool, GitError> {
Ok(!stdout.trim().is_empty())
}
-/// Get the worktree root directory (top-level of the working tree)
-pub fn get_worktree_root() -> Result<PathBuf, GitError> {
- get_worktree_root_in(std::path::Path::new("."))
-}
-
-/// Get the worktree root directory for a repository at the given path
+/// 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 we're currently in a worktree (vs the main repository)
-pub fn is_in_worktree() -> Result<bool, GitError> {
- is_in_worktree_in(std::path::Path::new("."))
-}
-
/// 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)?;
@@ -351,12 +311,7 @@ pub fn is_in_worktree_in(path: &std::path::Path) -> Result<bool, GitError> {
Ok(git_dir != common_dir)
}
-/// Check if base_branch is an ancestor of HEAD (i.e., would be a fast-forward)
-pub fn is_ancestor(base_branch: &str, head: &str) -> Result<bool, GitError> {
- is_ancestor_in(std::path::Path::new("."), base_branch, head)
-}
-
-/// Check if base is an ancestor of head in the repository at the given path
+/// 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])
@@ -367,11 +322,6 @@ pub fn is_ancestor_in(path: &std::path::Path, base: &str, head: &str) -> Result<
Ok(output.status.success())
}
-/// Count commits between base and head
-pub fn count_commits(base: &str, head: &str) -> Result<usize, GitError> {
- count_commits_in(std::path::Path::new("."), base, head)
-}
-
/// 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);
@@ -382,11 +332,6 @@ pub fn count_commits_in(path: &std::path::Path, base: &str, head: &str) -> Resul
.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(base: &str, head: &str) -> Result<bool, GitError> {
- has_merge_commits_in(std::path::Path::new("."), base, head)
-}
-
/// 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,
@@ -409,11 +354,6 @@ pub fn has_merge_commits_in(
Ok(!stdout.trim().is_empty())
}
-/// Get files changed between base and head
-pub fn get_changed_files(base: &str, head: &str) -> Result<Vec<String>, GitError> {
- get_changed_files_in(std::path::Path::new("."), base, head)
-}
-
/// Get files changed between base and head at the given path
pub fn get_changed_files_in(
path: &std::path::Path,
@@ -425,11 +365,6 @@ pub fn get_changed_files_in(
Ok(stdout.lines().map(|s| s.to_string()).collect())
}
-/// Get commit timestamp in seconds since epoch
-pub fn get_commit_timestamp(commit: &str) -> Result<i64, GitError> {
- get_commit_timestamp_in(std::path::Path::new("."), commit)
-}
-
/// 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))?;
@@ -439,14 +374,9 @@ pub fn get_commit_timestamp_in(path: &std::path::Path, commit: &str) -> Result<i
.map_err(|e| GitError::ParseError(format!("Failed to parse timestamp: {}", e)))
}
-/// Calculate commits ahead and behind between two refs
+/// Calculate commits ahead and behind at the given path
/// 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(base: &str, head: &str) -> Result<(usize, usize), GitError> {
- get_ahead_behind_in(std::path::Path::new("."), base, head)
-}
-
-/// Calculate commits ahead and behind at the given path
pub fn get_ahead_behind_in(
path: &std::path::Path,
base: &str,
@@ -457,25 +387,15 @@ pub fn get_ahead_behind_in(
Ok((ahead, behind))
}
-/// Get line diff statistics for working tree changes (unstaged + staged)
+/// 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() -> Result<(usize, usize), GitError> {
- get_working_tree_diff_stats_in(std::path::Path::new("."))
-}
-
-/// Get line diff statistics for working tree changes at the given path
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 (using three-dot diff for merge base)
+/// 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(base: &str, head: &str) -> Result<(usize, usize), GitError> {
- get_branch_diff_stats_in(std::path::Path::new("."), base, head)
-}
-
-/// Get line diff statistics between two refs at the given path
pub fn get_branch_diff_stats_in(
path: &std::path::Path,
base: &str,
@@ -521,11 +441,6 @@ fn parse_numstat(output: &str) -> Result<(usize, usize), GitError> {
Ok((total_added, total_deleted))
}
-/// Get all branch names (local and remote)
-pub fn get_all_branches() -> Result<Vec<String>, GitError> {
- get_all_branches_in(std::path::Path::new("."))
-}
-
/// 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> {
@@ -544,7 +459,7 @@ pub fn get_all_branches_in(path: &std::path::Path) -> Result<Vec<String>, GitErr
/// 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()?;
+ let all_branches = get_all_branches_in(std::path::Path::new("."))?;
// Get worktrees (always operates on current git repository)
let worktrees = list_worktrees()?;
@@ -560,11 +475,7 @@ pub fn get_available_branches() -> Result<Vec<String>, GitError> {
.collect())
}
-/// Get the merge base between two commits
-pub fn get_merge_base(commit1: &str, commit2: &str) -> Result<String, GitError> {
- get_merge_base_in(std::env::current_dir().unwrap().as_path(), commit1, commit2)
-}
-
+/// Get the merge base between two commits at the given path
pub fn get_merge_base_in(
path: &std::path::Path,
commit1: &str,
@@ -574,11 +485,7 @@ pub fn get_merge_base_in(
Ok(output.trim().to_string())
}
-/// Get commit subjects (first line of commit message) from a range
-pub fn get_commit_subjects(range: &str) -> Result<Vec<String>, GitError> {
- get_commit_subjects_in(std::env::current_dir().unwrap().as_path(), range)
-}
-
+/// 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,
@@ -587,11 +494,7 @@ pub fn get_commit_subjects_in(
Ok(output.lines().map(|s| s.to_string()).collect())
}
-/// Check if there are staged changes
-pub fn has_staged_changes() -> Result<bool, GitError> {
- has_staged_changes_in(std::env::current_dir().unwrap().as_path())
-}
-
+/// 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"])
diff --git a/src/main.rs b/src/main.rs
index f46444376..8ceca20f3 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -2,15 +2,16 @@ use anstyle::{AnsiColor, Color, Style};
use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::{Shell as CompletionShell, generate};
use rayon::prelude::*;
+use std::path::Path;
use std::process;
use worktrunk::config::{format_worktree_path, load_config};
use worktrunk::error_format::{format_error, format_error_with_bold, format_hint, format_warning};
use worktrunk::git::{
- GitError, Worktree, branch_exists, count_commits, get_ahead_behind_in, get_all_branches,
- get_available_branches, get_branch_diff_stats_in, get_changed_files, get_commit_subjects,
- get_commit_timestamp_in, get_current_branch, get_current_branch_in, get_default_branch,
- get_git_common_dir, get_merge_base, get_working_tree_diff_stats_in, get_worktree_root,
- has_merge_commits, has_staged_changes, is_ancestor, is_dirty, is_dirty_in, is_in_worktree,
+ GitError, Worktree, branch_exists_in, count_commits_in, get_ahead_behind_in,
+ get_all_branches_in, get_available_branches, get_branch_diff_stats_in, get_changed_files_in,
+ get_commit_subjects_in, get_commit_timestamp_in, get_current_branch_in, get_default_branch_in,
+ get_git_common_dir_in, get_merge_base_in, get_working_tree_diff_stats_in, get_worktree_root_in,
+ has_merge_commits_in, has_staged_changes_in, is_ancestor_in, is_dirty_in, is_in_worktree_in,
list_worktrees, worktree_for_branch,
};
use worktrunk::shell;
@@ -502,7 +503,7 @@ fn handle_switch(
worktree_path_template: &str,
) -> Result<(), GitError> {
// Check for conflicting conditions
- if create && branch_exists(branch)? {
+ if create && branch_exists_in(Path::new("."), branch)? {
return Err(GitError::CommandFailed(format_error_with_bold(
"Branch '",
branch,
@@ -535,7 +536,7 @@ fn handle_switch(
}
// No existing worktree, create one
- let git_common_dir = get_git_common_dir()?
+ let git_common_dir = get_git_common_dir_in(Path::new("."))?
.canonicalize()
.map_err(|e| GitError::CommandFailed(format!("Failed to canonicalize path: {}", e)))?;
@@ -596,16 +597,16 @@ fn handle_switch(
fn handle_remove(internal: bool) -> Result<(), GitError> {
// Check for uncommitted changes
- if is_dirty()? {
+ if is_dirty_in(Path::new("."))? {
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()?;
- let default_branch = get_default_branch()?;
- let in_worktree = is_in_worktree()?;
+ 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("."))?;
// If we're on default branch and not in a worktree, nothing to do
if !in_worktree && current_branch.as_deref() == Some(&default_branch) {
@@ -617,8 +618,8 @@ 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()?;
- let common_dir = get_git_common_dir()?
+ let worktree_root = get_worktree_root_in(Path::new("."))?;
+ let common_dir = get_git_common_dir_in(Path::new("."))?
.canonicalize()
.map_err(|e| GitError::CommandFailed(format!("Failed to canonicalize path: {}", e)))?;
@@ -674,11 +675,11 @@ fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), Gi
// Get target branch (default to default branch if not provided)
let target_branch = match target {
Some(b) => b.to_string(),
- None => get_default_branch()?,
+ None => get_default_branch_in(Path::new("."))?,
};
// Check if it's a fast-forward
- if !is_ancestor(&target_branch, "HEAD")? {
+ if !is_ancestor_in(Path::new("."), &target_branch, "HEAD")? {
let error_msg =
format_error_with_bold("Not a fast-forward from '", &target_branch, "' to HEAD");
let hint_msg = format_hint(
@@ -691,7 +692,7 @@ fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), Gi
}
// Check for merge commits unless allowed
- if !allow_merge_commits && has_merge_commits(&target_branch, "HEAD")? {
+ if !allow_merge_commits && has_merge_commits_in(Path::new("."), &target_branch, "HEAD")? {
return Err(GitError::CommandFailed(format_error(
"Found merge commits in push range. Use --allow-merge-commits to push non-linear history.",
)));
@@ -718,7 +719,7 @@ fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), Gi
// Check if target worktree is dirty
if is_dirty_in(wt_path)? {
// Get files changed in the push
- let push_files = get_changed_files(&target_branch, "HEAD")?;
+ let push_files = get_changed_files_in(Path::new("."), &target_branch, "HEAD")?;
// Get files changed in the worktree
let wt_status_output = process::Command::new("git")
@@ -760,7 +761,7 @@ fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), Gi
}
// Count commits and show info
- let commit_count = count_commits(&target_branch, "HEAD")?;
+ let commit_count = count_commits_in(Path::new("."), &target_branch, "HEAD")?;
if commit_count > 0 {
let commit_text = if commit_count == 1 {
"commit"
@@ -774,7 +775,7 @@ fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), Gi
}
// Get git common dir for the push
- let git_common_dir = get_git_common_dir()?;
+ let git_common_dir = get_git_common_dir_in(Path::new("."))?;
// Perform the push
let push_result = process::Command::new("git")
@@ -797,13 +798,13 @@ fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), Gi
fn handle_squash(target_branch: &str) -> Result<(), GitError> {
// Get merge base with target branch
- let merge_base = get_merge_base("HEAD", target_branch)?;
+ let merge_base = get_merge_base_in(Path::new("."), "HEAD", target_branch)?;
// Count commits since merge base
- let commit_count = count_commits(&merge_base, "HEAD")?;
+ let commit_count = count_commits_in(Path::new("."), &merge_base, "HEAD")?;
// Check if there are staged changes
- let has_staged = has_staged_changes()?;
+ let has_staged = has_staged_changes_in(Path::new("."))?;
// Handle different scenarios
if commit_count == 0 && !has_staged {
@@ -833,7 +834,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(&range)?;
+ let subjects = get_commit_subjects_in(Path::new("."), &range)?;
// Build deterministic commit message
let mut commit_message = format!("Squash commits from {}\n\n", target_branch);
@@ -877,13 +878,13 @@ fn handle_squash(target_branch: &str) -> Result<(), GitError> {
fn handle_merge(target: Option<&str>, squash: bool, keep: bool) -> Result<(), GitError> {
// Get current branch
- let current_branch = get_current_branch()?
+ let current_branch = get_current_branch_in(Path::new("."))?
.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()?,
+ None => get_default_branch_in(Path::new("."))?,
};
// Check if already on target branch
@@ -893,7 +894,7 @@ fn handle_merge(target: Option<&str>, squash: bool, keep: bool) -> Result<(), Gi
}
// Check for uncommitted changes
- if is_dirty()? {
+ if is_dirty_in(Path::new("."))? {
return Err(GitError::CommandFailed(format_error(
"Working tree has uncommitted changes. Commit or stash them first.",
)));
@@ -929,7 +930,7 @@ fn handle_merge(target: Option<&str>, squash: bool, keep: bool) -> Result<(), Gi
println!("Cleaning up worktree...");
// Get primary worktree path before finishing (while we can still run git commands)
- let common_dir = get_git_common_dir()?
+ let common_dir = get_git_common_dir_in(Path::new("."))?
.canonicalize()
.map_err(|e| GitError::CommandFailed(format!("Failed to canonicalize path: {}", e)))?;
let primary_worktree_dir = common_dir
@@ -1035,7 +1036,7 @@ fn handle_complete(args: Vec<String>) -> Result<(), GitError> {
| CompletionContext::MergeTarget
| CompletionContext::BaseFlag => {
// Complete with all branches
- let branches = get_all_branches().unwrap_or_else(|e| {
+ let branches = get_all_branches_in(Path::new(".")).unwrap_or_else(|e| {
if std::env::var("WT_DEBUG_COMPLETION").is_ok() {
eprintln!("completion error: {}", e);
}